package com.example.controller.pc;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.result.Result;
import com.example.entity.dto.User.HzUserDeptInfo;
import com.example.entity.excel.*;
import com.example.entity.hz.SFCTA;
import com.example.entity.mysql.Productprocessresource;
import com.example.entity.mysql.Resource;
import com.example.entity.mysql.Resourcegroup;
import com.example.entity.vo.ItemVo2;
import com.example.entity.vo.hzView.HzMoctbView;
import com.example.entity.yifei.*;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.hzViewSync.HzViewSyncMapper;
import com.example.service.*;
import com.example.service.pc.ProductprocessresourceService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.untils.TimeUtils;
import com.github.houbb.opencc4j.util.ZhTwConverterUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "杂项")
@RequestMapping("/api/za")
public class ZaController {

    @Autowired
    private CoptdMapper coptdMapper;

    @Autowired
    private CoptdService coptdService;

    @Autowired
    private InvmbMapper invmbMapper;

    @Autowired
    private InvmbService invmbService;

    @Autowired
    private PurtdMapper purtdMapper;

    @Autowired
    private PurtdService purtdService;

    @Autowired
    private SfctaMapper sfctaMapper;

    @Autowired
    private SfctaService sfctaService;

    @Autowired
    private CmsmdService cmsmdService;

    @Autowired
    private PurmaService purmaService;
    @Autowired
    private DscmaMapper dscmaMapper;

    @Autowired
    private HzViewSyncMapper hzViewSyncMapper;
    @Autowired
    private TablesynclogService tablesynclogService;
    @Autowired
    private MoctbService moctbService;
    @Autowired
    private MoctbMapper mapper;
//
//    @ApiOperation("MOCTB批量更新")
//    @GetMapping("moctbPLGX")
//    @DSTransactional
//    public Result moctbPLGX() {
//        List<Moctb> moctbs = new ArrayList<>();
//        Moctb moctb = new Moctb();
//        moctb.setTb001("AMM1");  moctb.setTb002("AMM2024-008049-01");  moctb.setUdf03("51");  moctb.setUdf01(""); moctb.setUdf02("");
//        moctbs.add(moctb);
//        Moctb moctb2 = new Moctb();
//        moctb2.setTb001("AMM1");  moctb2.setTb002("AMM2024-008197-01");  moctb2.setUdf03("51");  moctb2.setUdf01(""); moctb2.setUdf02("");
//        moctbs.add(moctb2);
//        Moctb moctb3 = new Moctb();
//        moctb3.setTb001("AMM1");  moctb3.setTb002("AMM2024-008623-01");  moctb3.setUdf03("51");  moctb3.setUdf01(""); moctb3.setUdf02("");
//        moctbs.add(moctb3);
////        mapper.updateByMultiId(moctb3);
//        moctbService.updateBatchByMultiId(moctbs);
//        return Result.success();
//    }

    @ApiOperation("测试实体类封装")
    @GetMapping("testHzMoctbView")
    public Result testHzMoctbView() {
        Tablesynclog moctbLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTB"));
        List<HzMoctbView> moctbViewList = hzViewSyncMapper.hzMoctbViewList(moctbLog.getLastsynctime());
        return Result.success(moctbViewList);
    }


    @ApiOperation("coptdCopy")
    @GetMapping("coptdCopy")
    public Result coptdCopy() {
        List<Coptd> list = coptdMapper.all();
        DynamicDataSourceContextHolder.push("demo");
        coptdService.saveBatch(list);
        return Result.success();
    }

    @ApiOperation("invmbCopy")
    @GetMapping("invmbCopy")
    public Result invmbCopy() {
        List<Invmb> list = invmbMapper.all();
        DynamicDataSourceContextHolder.push("demo");
        invmbService.saveBatch(list);
        return Result.success();
    }

    @ApiOperation("purtdCopy")
    @GetMapping("purtdCopy")
    public Result purtdCopy() {
        List<Purtd> list = purtdMapper.all();
        DynamicDataSourceContextHolder.push("demo");
        purtdService.saveBatch(list);
        return Result.success();
    }

    @ApiOperation("sfctaCopy")
    @GetMapping("sfctaCopy")
    public Result sfctaCopy() {
        List<SFCTA> list = sfctaMapper.all();
        DynamicDataSourceContextHolder.push("demo");
        sfctaService.saveBatch(list);
        return Result.success();
    }

    @ApiOperation("工作中心列表")
    @PostMapping("workCenterList")
    public Result<List<Cmsmd>> workCenterList() {
        return Result.success(cmsmdService.list());
    }

    @ApiOperation("工作中心/委外供应商列表")
    @PostMapping("workCenterSupplierList")
    public Result<List<ItemVo2>> workCenterSupplierList() {
        List<Purma> list = purmaService.list();
        List<Cmsmd> list1 = cmsmdService.list();
        List<ItemVo2> res = new ArrayList<>();
        for(Cmsmd cmsmd : list1) {
            res.add(new ItemVo2(cmsmd.getMd001(), cmsmd.getMd002()));
        }
        for(Purma purma : list) {
            res.add(new ItemVo2(purma.getMa001(), purma.getMa002()));
        }
        return Result.success(res);
    }

    @Autowired
    private ResourcegroupService resourcegroupService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private CmsmwService cmsmwService;

    @Autowired
    private CmsmwMapper cmsmwMapper;

    @Autowired
    private BommfService bommfService;

    @Autowired
    private ProductprocessresourceService productprocessresourceService;

    @DSTransactional
    @ApiOperation("排产EXCEL导入, 设备组信息")
    @PostMapping("excelDeviceGroup")
    public void excelDeviceGroup(@RequestPart("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, ResourceGroupExcel.class, new PageReadListener<ResourceGroupExcel>(dataList -> {
            for (ResourceGroupExcel resourceGroupExcel : dataList) {
                Resourcegroup resourcegroup = new Resourcegroup();
                resourcegroup.setResourceGroupNO(resourceGroupExcel.getResourceGroup());
                resourcegroup.setResourceGroupName(resourceGroupExcel.getResourceGroupName());
                resourcegroup.setResourceGroupParentId(1);
                resourcegroup.setType("M");
                resourcegroupService.save(resourcegroup);
                System.out.println(resourceGroupExcel);
//                System.out.println(resourceGroupExcel);
//                originalExcelList.add(cp);
//                saleExcelList.add(convertToSimplifiedChinese(saleExcel));
            }
        })).sheet().doRead();
    }

    @DSTransactional
    @ApiOperation("排产EXCEL导入, 设备清单")
    @PostMapping("excelDevice")
    public void excelDevice(@RequestPart("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, DeviceExcel.class, new PageReadListener<DeviceExcel>(dataList -> {
            for (DeviceExcel deviceExcel : dataList) {
                if(deviceExcel.getResourceParentId() == null) {
                    throw new CustomException("500", "设备组不能为空");
                }
                Resourcegroup one = resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>()
                        .eq(Resourcegroup::getResourceGroupNO, deviceExcel.getResourceParentId()));
                if(one == null) {
                    throw new CustomException("500", "设备组不存在");
                }
                Resourcegroup resourcegroup = new Resourcegroup();
                resourcegroup.setResourceGroupNO(deviceExcel.getResourceNo());
                resourcegroup.setResourceGroupName(deviceExcel.getResourceName());
                resourcegroup.setResourceGroupParentId(one.getResourceGroupId());
                resourcegroup.setType("F");
                resourcegroupService.save(resourcegroup);

                Resource resource = new Resource();
                resource.setResourceType(1);
                resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
                resource.setResourceGroupId(one.getResourceGroupId());
                resource.setDeviceid(deviceExcel.getResourceNo());
                resource.setDevicename(deviceExcel.getResourceName());
                resource.setManufacturer(deviceExcel.getManufacturer());
                resource.setUsedepartment(deviceExcel.getUseDepartment());
                resourceService.save(resource);

//                 System.out.println(deviceExcel);

//                originalExcelList.add(cp);
//                saleExcelList.add(convertToSimplifiedChinese(saleExcel));
            }
        })).sheet().doRead();
    }

    @DSTransactional
    @ApiOperation("排产EXCEL导入, 产品工艺路线")
    @PostMapping("excelProductProcess")
    public void excelProductProcess(@RequestPart("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        // 校验该资源组是否属于该资源类别
        List<Resourcegroup> list333 = resourcegroupService.list();
        Map<Integer, Resourcegroup> posMap = new HashMap<>();
        Map<String, Resourcegroup> resourceGroupNOMap = new HashMap<>();
        for(Resourcegroup t : list333) {
            posMap.put(t.getResourceGroupId(), t);
            resourceGroupNOMap.put(t.getResourceGroupNO(), t);
        }
        Map<String, String> mw001Map = new HashMap<>();
        EasyExcel.read(inputStream, ProductProcessExcel.class, new PageReadListener<ProductProcessExcel>(dataList -> {
            for (ProductProcessExcel productProcessExcel : dataList) {
//                System.out.println(productProcessExcel);
                String simple = ZhTwConverterUtil.toSimple(productProcessExcel.getProcessName());
                Productprocessresource p = new Productprocessresource();
                p.setProductId(productProcessExcel.getProductNumber());

                List<Cmsmw> list = null;
                if(mw001Map.get(simple) == null) {
                    list = cmsmwMapper.cmsmwByMw003(simple);
                    if(list == null || list.size() == 0) {
                        throw new CustomException("500", "工艺信息档中不存在此工艺");
                    }
                    if(list.size() > 1) {
                        throw new CustomException("500", "工艺信息档中存在多个此工艺");
                    }
                    mw001Map.put(simple, list.get(0).getMw001());
                    p.setProcessId(list.get(0).getMw001());
                }else{
                    p.setProcessId(mw001Map.get(simple));
                }
                List<Bommf> bommfList = bommfService.list(new LambdaQueryWrapper<Bommf>().eq(Bommf::getMf001, productProcessExcel.getProductNumber())
                        .and(q -> q.apply("cast(MF008 as nvarchar) = '" + simple + "'")));
                if(bommfList == null || bommfList.size() == 0 || bommfList.size() > 1)  continue;
                p.setProcessNo(bommfList.get(0).getMf003());
                p.setBeat(productProcessExcel.getBeat());
                p.setWages(productProcessExcel.getWages());
                p.setPreparationTime(productProcessExcel.getPreparationTime());
                p.setMachiningCenter(productProcessExcel.getMachiningCenter());
                Resourcegroup resourcegroup = resourceGroupNOMap.get(productProcessExcel.getResourceGroup());
                if(resourcegroup == null) {
                    throw new CustomException("500", "资源组编号不存在");
                }
                p.setResourceGroupId(resourcegroup.getResourceGroupId());
                p.setResourceTypeId(resourcegroupService.getOriginIdById(resourcegroup.getResourceGroupId(), posMap));
                int count = productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>()
                        .eq(Productprocessresource::getProductId, productProcessExcel.getProductNumber())
                        .eq(Productprocessresource::getProcessNo, p.getProcessNo())
                        .eq(Productprocessresource::getProcessId, p.getProcessId())
                        .eq(Productprocessresource::getPrimaryCode, 1)
                        .eq(Productprocessresource::getResourceTypeId, 1));
                count += productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>()
                        .eq(Productprocessresource::getProductId, productProcessExcel.getProductNumber())
                        .eq(Productprocessresource::getProcessNo, p.getProcessNo())
                        .eq(Productprocessresource::getProcessId, p.getProcessId())
                        .eq(Productprocessresource::getPrimaryCode, 1)
                        .eq(Productprocessresource::getResourceTypeId, 2));
                if(count == 0) {
                    p.setPrimaryCode(1);
                }

                if(productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>().eq(Productprocessresource::getProductId, p.getProductId())
                        .eq(Productprocessresource::getProcessNo, p.getProcessNo())
                        .eq(Productprocessresource::getProcessId, p.getProcessId())
                        .eq(Productprocessresource::getResourceGroupId, p.getResourceGroupId())) == 0) {
                    productprocessresourceService.save(p);
                }

            }
        })).sheet().doRead();
    }

    @DSTransactional
    @ApiOperation("排产EXCEL导入, 模具清单")
    @PostMapping("excelModelList")
    public void excelModelList(@RequestPart("file") MultipartFile file) throws Exception {
        Map<String, Integer> idMap = new HashMap<>();
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, ModelExcel.class, new PageReadListener<ModelExcel>(dataList -> {
            for (ModelExcel model : dataList) {
                Integer s = idMap.get(model.getMouldName());
                if(s == null) {
                    Resourcegroup resourcegroupA = new Resourcegroup();
                    resourcegroupA.setResourceGroupNO("T-" + model.getMouldNo());
                    resourcegroupA.setResourceGroupName(model.getMouldName());
                    resourcegroupA.setResourceGroupParentId(3);
                    resourcegroupA.setType("M");
                    resourcegroupService.save(resourcegroupA);
                    idMap.put(model.getMouldName(), resourcegroupA.getResourceGroupId());
                }
                Resourcegroup resourcegroup = new Resourcegroup();
                resourcegroup.setResourceGroupNO(model.getMouldNo());
                resourcegroup.setResourceGroupName(model.getMouldName());
                resourcegroup.setResourceGroupParentId(idMap.get(model.getMouldName()));
                resourcegroup.setType("F");
                resourcegroupService.save(resourcegroup);

                Resource resource = new Resource();
                resource.setResourceType(3);
                resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
                resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
                resource.setDeviceid(model.getMouldNo());
                resource.setDevicename(model.getMouldName());
                resource.setMouldDrawNo(model.getMouldDrawNo());
                resource.setCavityNumber(Integer.parseInt(model.getCavityNumber()));
                resource.setCavitySpecifications(model.getCavitySpecifications());
                resource.setDesignLife(model.getDesignLife());
                resource.setUsedNumber(model.getUsedNumber());
                resource.setMaintenanceCycle(model.getMaintenanceCycle());
                resource.setAffiliation(model.getAffiliation());
                resource.setRemark(model.getRemark());
                resourceService.save(resource);
            }
        })).sheet().doRead();
    }

    @DSTransactional
    @ApiOperation("排产EXCEL导入, 注塑生产信息")
    @PostMapping("excelZSSCXX")
    public void excelZSSCXX(@RequestPart("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, ZSSCXXExcel.class, new PageReadListener<ZSSCXXExcel>(dataList -> {
            for (ZSSCXXExcel zs : dataList) {
                // 查到的是具体的模具（末级）
                Resourcegroup one = resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, zs.getMouldDrawNo()));
                if(productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>().eq(Productprocessresource::getProductId, zs.getProductId())
                        .eq(Productprocessresource::getProcessNo, "0010")
                        .eq(Productprocessresource::getProcessId, "1001")
                        .eq(Productprocessresource::getResourceGroupId, one.getResourceGroupParentId())) == 0) {
                    Productprocessresource p = new Productprocessresource();
                    p.setProductId(zs.getProductId());
                    p.setProcessNo("0010");
                    p.setProcessId("1001");
                    p.setResourceGroupId(one.getResourceGroupParentId());
                    p.setResourceTypeId(3);
                    p.setBeat(zs.getBeat());
                    p.setUseCavityNumber(zs.getUseCavityNumber());
                    p.setCavityPlace(zs.getCavityPlace());
                    p.setMoldChangeTime(zs.getMoldChangeTime());
                    if(productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>().eq(Productprocessresource::getProductId, zs.getProductId())
                            .eq(Productprocessresource::getProcessNo, "0010")
                            .eq(Productprocessresource::getProcessId, "1001")
                            .eq(Productprocessresource::getPrimaryCode,1)
                            .eq(Productprocessresource::getResourceTypeId, 3)) == 0) {
                        p.setPrimaryCode(1);
                    }
                    productprocessresourceService.save(p);
                }

                // 查的是设备组（统驭）
                one = resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, zs.getResourceGroup()));
                if(productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>().eq(Productprocessresource::getProductId, zs.getProductId())
                        .eq(Productprocessresource::getProcessNo, "0010")
                        .eq(Productprocessresource::getProcessId, "1001")
                        .eq(Productprocessresource::getResourceGroupId, one.getResourceGroupId())) == 0) {
                    Productprocessresource p22 = new Productprocessresource();
                    p22.setProductId(zs.getProductId());
                    p22.setProcessNo("0010");
                    p22.setProcessId("1001");
                    p22.setResourceGroupId(one.getResourceGroupId());
                    p22.setResourceTypeId(1);
                    p22.setBeat(zs.getBeat());
                    if(productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>().eq(Productprocessresource::getProductId, zs.getProductId())
                            .eq(Productprocessresource::getProcessNo, "0010")
                            .eq(Productprocessresource::getProcessId, "1001")
                            .and(i -> i.eq(Productprocessresource::getResourceTypeId, 1).or().eq(Productprocessresource::getResourceTypeId, 2))
                            .eq(Productprocessresource::getPrimaryCode,1)) == 0) {
                        p22.setPrimaryCode(1);
                    }
                    productprocessresourceService.save(p22);
                }

            }
        })).sheet().doRead();
    }

    @ApiOperation("测试实体类封装")
    @PostMapping("/testHzUserDeptInfo")
    @DSTransactional
    public void testHzUserDeptInfo(@RequestPart("file") MultipartFile file,
                                     HttpServletResponse response) throws IOException {

        InputStream inputStream = file.getInputStream();
        List<HzUserDeptInfo> excelList = new ArrayList<>();
        EasyExcel.read(inputStream, HzUserDeptInfo.class, new PageReadListener<HzUserDeptInfo>(dataList -> {
            for (HzUserDeptInfo item : dataList) {
                excelList.add(item);
            }
        })).sheet().doRead();
        System.out.println(excelList);

        List<Dscma> dscmas = dscmaMapper.selectList(null);
        Map<String, Dscma> map = new HashMap<>();
        for(Dscma t : dscmas) {
            map.put(t.getMa001().trim(), t);
        }
        List<HzUserDeptInfo> needAddList = new ArrayList<>();
        for(HzUserDeptInfo t : excelList) {
            Dscma dscma = map.get(t.getUserNo().trim());
            if(dscma == null) {
                needAddList.add(t);
                continue;
            }
            dscma.setUdf01(t.getDeptNo());
            dscmaMapper.update(dscma, new LambdaQueryWrapper<Dscma>().eq(Dscma::getMa001, t.getUserNo()));
        }

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        String fullNowTime = TimeUtils.getFullNowTime().replace(":", "-");
        // 追加新数据到第1个Sheet
        WriteSheet newSheet = EasyExcel.writerSheet(0, "导出结果" + fullNowTime)
                .head(HzUserDeptInfo.class).build();

        excelWriter.write(needAddList, newSheet);

        excelWriter.finish();

        response.getOutputStream().close();

    }

}
